package com.youku.mson.serializer;

import java.util.Map;
import java.util.Map.Entry;

import com.youku.mson.util.Assert;

public class MapSerializer implements JsonSerializer {

	@Override
	public void serialize(JsonWriter out, Object target) {
		if (target == null) {
			out.writeNull();
		} else {
			out.beginObject();

			Map<?, ?> map = (Map<?, ?>) target;

			for (Entry<?, ?> entry : map.entrySet()) {
				Object key = entry.getKey();
				Assert.notNull("map" + map + "的key不能为空", key);
				Object value = entry.getValue();

				out.writeString(key);
				out.writeColon();

				JsonSerializer serializer = JsonSerializerFactory.getSerializer(value.getClass());

				serializer.serialize(out, value);
				out.writeComma();
			}

			if (out.endWith(",")) {
				out.deleteEnd();
			}

			out.endObject();
		}
	}

}
